package com.uziot.bucket.boot.message.convert;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * @author shidt
 * @version V1.0
 * @className FastJsonMessageConverterAdapter
 * @date 2021-07-30 10:15:31
 * @description
 */

public class FastJsonMessageConverterAdapter extends FastJsonHttpMessageConverter {
    /**
     * 根据控制器类型和入参类型来判定能否读入并解析对象
     *
     * @param type         控制器的入参类型
     * @param contextClass 控制器的Class对象
     * @param mediaType    媒体类型
     * @return 是否能读入内容
     */
    @Override
    public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
        return super.canRead(type, contextClass, mediaType);
    }

    /**
     * 根据控制器的类型和返回参数判定能否写出对象
     *
     * @param type      返回响应参数的类型
     * @param clazz     控制器的Class对象
     * @param mediaType 媒体类型
     * @return 是否能够执行写出类型
     */
    @Override
    public boolean canWrite(Type type, Class<?> clazz, MediaType mediaType) {
        return super.canWrite(type, clazz, mediaType);
    }

    /**
     * 读入内容处理后返回控制器的对象
     *
     * @param type         入参类型
     * @param contextClass 控制器的class对象
     * @param inputMessage 输入的消息报文对象
     * @return 个性化解析后的对象
     * @throws IOException                     异常
     * @throws HttpMessageNotReadableException 无法重复读入异常
     */
    @Override
    public Object read(Type type, Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        String typeName = type.getTypeName();
        if ("java.lang.String".equals(typeName)) {
            return StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset());
        }
        return super.read(type, contextClass, inputMessage);
    }

    /**
     * 控制器实际写出的对象作为响应报文
     *
     * @param o             控制器返回的对象
     * @param type          控制器返回的对象类型
     * @param contentType   内容类型ContentType
     * @param outputMessage 输出的消息对象
     * @throws IOException                     IO异常
     * @throws HttpMessageNotWritableException 写出异常
     */
    @Override
    public void write(Object o, Type type, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        super.write(o, type, contentType, outputMessage);
    }
}
